import os
from PIL import Image, ImageDraw, ImageFont
import argparse

def create_character_image(font_path, char, output_dir, size=(100, 100), bg_color=(255, 255, 255), text_color=(0, 0, 0)):
    """
    为单个字符创建PNG图片
    """
    # 创建图片
    image = Image.new('RGB', size, bg_color)
    draw = ImageDraw.Draw(image)
    
    # 加载字体
    font_size = int(size[0] * 0.8)  # 字体大小设为图片宽度的80%
    font = ImageFont.truetype(font_path, font_size)
    
    # 计算文字位置使其居中
    text_bbox = draw.textbbox((0, 0), char, font=font)
    text_width = text_bbox[2] - text_bbox[0]
    text_height = text_bbox[3] - text_bbox[1]
    
    x = (size[0] - text_width) // 2
    y = (size[1] - text_height) // 2
    
    # 绘制文字
    draw.text((x, y), char, font=font, fill=text_color)
    
    # 保存图片
    output_path = os.path.join(output_dir, f"{ord(char):04x}.png")
    image.save(output_path)

def process_font(font_path, output_dir, size=(100, 100)):
    """
    处理字体文件，为每个字符生成PNG图片
    """
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    
    # 加载字体
    font = ImageFont.truetype(font_path)
    
    # 获取字体支持的所有字符
    chars = set()
    for i in range(0x4E00, 0x9FFF + 1):  # 常用汉字范围
        try:
            char = chr(i)
            font.getbbox(char)
            chars.add(char)
        except:
            continue
    
    # 为每个字符生成图片
    for char in chars:
        create_character_image(font_path, char, output_dir, size)
        print(f"已生成字符 {char} 的图片")

def main():
    parser = argparse.ArgumentParser(description='将TTF字体文件转换为PNG图片')
    parser.add_argument('font_dir', help='包含TTF字体文件的目录')
    parser.add_argument('--output', '-o', default='output', help='输出目录')
    parser.add_argument('--size', '-s', type=int, default=100, help='输出图片的大小（像素）')
    
    args = parser.parse_args()
    
    # 遍历字体目录
    for filename in os.listdir(args.font_dir):
        if filename.lower().endswith('.ttf'):
            font_path = os.path.join(args.font_dir, filename)
            font_name = os.path.splitext(filename)[0]
            output_dir = os.path.join(args.output, font_name)
            
            print(f"正在处理字体: {filename}")
            process_font(font_path, output_dir, size=(args.size, args.size))
            print(f"字体 {filename} 处理完成")

if __name__ == '__main__':
    main() 